package com.jone.phone.detail;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.Dialog;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.CallLog;
import android.util.Log;
import android.view.Window;

import com.jone.phone.detail.db.ConfigCenter;
import com.jone.phone.detail.model.DayStat;
import com.jone.phone.detail.model.MonthStat;
import com.jone.phone.detail.service.BackService;
import com.jone.phone.detail.ui.TodayView;
import com.jone.phone.detail.util.Constants;
import com.jone.phone.detail.util.DateUtil;

public class MainActivity extends Activity {
	
	private static final int LOAD_FINISH = 1;
	
	private static final int LOAD_DIALOG = 2;
	
	private static final String[] TELE_PROJECTION = {
		CallLog.Calls.TYPE,CallLog.Calls.NUMBER,CallLog.Calls.DATE,CallLog.Calls.DURATION,
		CallLog.Calls.NEW,CallLog.Calls.CACHED_NAME,
	};
	
	private static final String[] SMS_PROJECTION = {
		"address","person","date","type",
	};
	
	private Handler handler = new Handler(){
		  public void handleMessage(Message message){
		   switch(message.what){
		   case LOAD_FINISH:	
		    	dismissDialog(LOAD_DIALOG);	
		    	Intent i = new Intent(MainActivity.this,TodayView.class);
		        startActivity(i);
		    	break;
		   }
		  }
	};	
	
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);         
        setContentView(R.layout.main);
        
        if(!BackService.isRunning){
        	BackService.isRunning = true;
        	Intent i = new Intent(getApplicationContext(),BackService.class);
        	getApplicationContext().startService(i);
        }
        
        
        String installDay = ConfigCenter.getValue(this, Constants.KEY_INSTALL_DAY, "");
        if("".equals(installDay)){
        	ConfigCenter.setValue(this, Constants.KEY_INSTALL_DAY, DateUtil.getCurrentDate("yyyyMMdd"));
        }
        
        NotificationManager nfManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    	nfManager.cancel(114);
    	nfManager.cancel(115);
    	
        new Thread(){
        	public void run(){
        		long before = System.currentTimeMillis();
        		boolean historyFinish = ConfigCenter.getValue(getApplicationContext(), Constants.KEY_LOAD_HISTORY_FINISHED, false);
        		if(!historyFinish){
        			loadHistory();
        		}
        		
        		Log.d("Time", "loadCallLog time:"+(System.currentTimeMillis()-before));
        		
        		Message loadFinish = new Message();
  			   	loadFinish.what = LOAD_FINISH;
     		    handler.sendMessage(loadFinish);
        	}        	
        }.start();
        
        showDialog(LOAD_DIALOG);
        
       
    }
    
    private void loadHistory(){   	
		
		//写入今日统计数据
		smsDayStat(Constants.MSG_IN);
		smsDayStat(Constants.MSG_OUT);	
		
		//写入本月统计数据
		smsMonthStat(Constants.MSG_IN);
		smsMonthStat(Constants.MSG_OUT);
		
		loadCallLog();
		ConfigCenter.setValue(getApplicationContext(), Constants.KEY_LOAD_HISTORY_FINISHED, true);
    }
    
    private int formatDuration(int value){
		if(value%60 !=0){
			return (value/60 + 1)*60;
		}else{
			return value;
		}
	}
    
    private boolean loadCallLog(){	
    	String month = DateUtil.getCurrentDate("yyyyMM");
    	Map<DayStat,DayStat> dayStatMap = new HashMap<DayStat,DayStat>();
		long beginTime = getFirstDayTime();
		long endTime = System.currentTimeMillis();
		//从本月第一天开始统计
		ContentResolver content = this.getContentResolver();
		String orderBy = CallLog.Calls.DATE + " asc";
		String selection = CallLog.Calls.DATE+">="+beginTime+" and "+CallLog.Calls.DATE+"<="+endTime;
		Cursor cursor = content.query(CallLog.Calls.CONTENT_URI, TELE_PROJECTION, selection, null, orderBy);
		if(cursor.moveToFirst()){
			while(!cursor.isAfterLast()){				
				int type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));
				int duration = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.DURATION));
				long ringTime = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE));	
				String day = DateUtil.formatDate(ringTime, "yyyyMMdd");
			
				if(duration > 0){
					
					duration = formatDuration(duration);
										
					//设置标志key
					String callType = "";
					if(type == CallLog.Calls.INCOMING_TYPE){
						callType = Constants.CALL_IN;
					}else if(type == CallLog.Calls.OUTGOING_TYPE){
						callType = Constants.CALL_OUT;
					}
					
					DayStat dayStat = new DayStat(day,callType,duration);
					if(dayStatMap.containsKey(dayStat)){
						dayStatMap.get(dayStat).addNum(dayStat.getNum());
					}else{
						dayStatMap.put(dayStat, dayStat);
					}
				}				
				cursor.moveToNext();
			}
			
			int monthCallOut = 0;
			int monthCallIn = 0;
			for(DayStat stat:dayStatMap.values()){
				if(stat.getKey().equals(Constants.CALL_OUT)){
					monthCallOut += stat.getNum();
				}else if(stat.getKey().equals(Constants.CALL_IN)){
					monthCallIn += stat.getNum();
				}
				ContentValues dValues = new ContentValues();
				dValues.put(DayStat.DAY, stat.getDay());
				dValues.put(DayStat.KEY, stat.getKey());
				dValues.put(DayStat.NUM, stat.getNum());
				this.getContentResolver().insert(DayStat.URI_DAY_STAT, dValues);
			}
			
			//插入月统计数据
			ContentValues mValues = new ContentValues();
			mValues.put(MonthStat.MONTH, month);
			mValues.put(MonthStat.KEY, Constants.CALL_OUT);
			mValues.put(MonthStat.NUM, monthCallOut);
			this.getContentResolver().insert(MonthStat.URI_MONTH_STAT, mValues);
			
			mValues = new ContentValues();
			mValues.put(MonthStat.MONTH, month);
			mValues.put(MonthStat.KEY, Constants.CALL_IN);
			mValues.put(MonthStat.NUM, monthCallIn);
			this.getContentResolver().insert(MonthStat.URI_MONTH_STAT, mValues);			
		}
		cursor.close();
		return true;		
	}	
    
    /**
	 * 本月短信统计
	 * @param inOutFlag
	 */
	private void smsMonthStat(String inOutFlag){
		long beginTime = getFirstDayTime();
		long endTime = System.currentTimeMillis();
		String selection = "date >="+beginTime+" and date <="+endTime;
		ContentResolver content = this.getContentResolver();
		String box = "";
		if(inOutFlag.equals(Constants.MSG_IN)){
			box = "inbox";
		}else{
			box = "sent";
		}
		Cursor cursor = content.query(Uri.parse("content://sms/"+box), SMS_PROJECTION, selection, null, null);
		if(cursor.moveToFirst()){			
			ContentValues mValues = new ContentValues();
			mValues.put(MonthStat.MONTH, DateUtil.getCurrentDate("yyyyMM"));
			mValues.put(MonthStat.KEY, inOutFlag);
			mValues.put(MonthStat.NUM, cursor.getCount());
			this.getContentResolver().insert(MonthStat.URI_MONTH_STAT, mValues);			
		}
		cursor.close();		
	}
	
	/**
	 * 今日短信统计
	 * @param inOutFlag
	 */
	private void smsDayStat(String inOutFlag){
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);	
		long beginTime = calendar.getTime().getTime();
		long endTime = System.currentTimeMillis();
		String selection = "date >="+beginTime+" and date <="+endTime;
		ContentResolver content = this.getContentResolver();
		String box = "";
		if(inOutFlag.equals(Constants.MSG_IN)){
			box = "inbox";
		}else{
			box = "sent";
		}
		Cursor cursor = content.query(Uri.parse("content://sms/"+box), SMS_PROJECTION, selection, null, null);
		if(cursor.moveToFirst()){			
			ContentValues mValues = new ContentValues();
			mValues.put(DayStat.DAY, DateUtil.getCurrentDate("yyyyMMdd"));
			mValues.put(DayStat.KEY, inOutFlag);
			mValues.put(DayStat.NUM, cursor.getCount());
			this.getContentResolver().insert(DayStat.URI_DAY_STAT, mValues);			
		}
		cursor.close();		
	}
	
	private long getFirstDayTime(){
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.DAY_OF_MONTH, 1);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);		
		//设置开始时间为本月第一天
		return calendar.getTime().getTime();
	}
    
    
    @Override
    protected Dialog onCreateDialog(int id) {    	
        switch (id) {           
            case LOAD_DIALOG: {
                ProgressDialog dialog = new ProgressDialog(this);
                dialog.setMessage("正在读取通话及短信历史记录...");
                dialog.setIndeterminate(true);
                dialog.setCancelable(true);
                return dialog;
            }
        }
        return null;
    }
    
    public void onStop(){
    	this.finish();
    	super.onDestroy();
    }
}